<template>
  <div class="training-record-container">
    <div class="header">
      <h1>训练记录</h1>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <div class="filter-content">
        <div class="filter-group">
          <h3>时间范围：</h3>
          <div class="date-inputs">
            <el-date-picker v-model="startDate" type="date" placeholder="开始日期" format="YYYY/MM/DD"
              value-format="YYYY-MM-DD" :disabled-date="disabledStartDate" />
            <span class="date-separator">至</span>
            <el-date-picker v-model="endDate" type="date" placeholder="结束日期" format="YYYY/MM/DD"
              value-format="YYYY-MM-DD" :disabled-date="disabledEndDate" />
          </div>
        </div>

        <div class="filter-group">
          <h3>关键字：</h3>
          <el-input v-model="keyword" placeholder="输入考试科目或年份" clearable class="keyword-input" />
        </div>

        <div class="filter-actions">
          <el-button type="primary" @click="handleSearch" class="search-btn">搜索</el-button>
          <el-button @click="handleReset" class="reset-btn">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 考试类型切换 -->
    <div class="exam-type-tabs">
      <el-button :type="activeTab === 'real' ? 'primary' : ''" @click="switchTab('real')" class="tab-btn">
        真题考试
      </el-button>
      <el-button :type="activeTab === 'mock' ? 'primary' : ''" @click="switchTab('mock')" class="tab-btn">
        组卷考试
      </el-button>
      <el-button :type="activeTab === 'daily' ? 'primary' : ''" @click="switchTab('daily')" class="tab-btn">
        每日练习
      </el-button>
    </div>

    <!-- 考试记录列表 -->
    <div class="exam-records">
      <div v-if="loading" class="loading">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="records.length === 0" class="no-data">
        <el-empty description="暂无记录" />
      </div>

      <div v-else class="record-list" :data-per-page="pageSize">
        <!-- 真题考试记录 -->
        <div v-if="activeTab === 'real'" 
             v-for="record in records" 
             :key="record.recordId"
             class="record-item">
          <div class="record-header">
            <span class="exam-type">{{ record.examType }}</span>
            <span class="exam-date">{{ formatDate(record.examDate) }}</span>
          </div>
          <div class="record-details">
            <div class="detail-item">
              <span class="detail-label">得分：</span>
              <span class="detail-value">{{ record.score }}/80</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">年份：</span>
              <span class="detail-value">{{ record.examYear }}</span>
            </div>
          </div>
          <div class="record-actions">
            <el-button type="text" class="detail-btn" @click="showRecordDetail(record.recordId)">
              查看详情
            </el-button>
          </div>
        </div>

        <!-- 组卷考试记录 -->
        <div v-if="activeTab === 'mock'" 
             v-for="record in records" 
             :key="record.examId"
             class="record-item">
          <div class="record-header">
            <span class="exam-type">{{ record.examType }}</span>
            <span class="exam-date">{{ formatDate(record.createdAt) }}</span>
          </div>
          <div class="record-details">
            <div class="detail-item">
              <span class="detail-label">得分：</span>
              <span class="detail-value">{{ record.score }}/80</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">策略：</span>
              <span class="detail-value">{{ record.examStrategy }}</span>
            </div>
          </div>
          <div class="record-actions">
            <el-button type="text" class="detail-btn" @click="showRecordDetail(record.examId)">
              查看详情
            </el-button>
          </div>
        </div>

        <!-- 每日练习记录 -->
        <div v-if="activeTab === 'daily'" 
             v-for="record in records" 
             :key="record.practiceId"
             class="record-item">
          <div class="record-header">
            <span class="exam-type">每日练习</span>
            <span class="exam-date">{{ formatDate(record.practiceDate) }}</span>
          </div>
          <div class="record-details">
            <div class="detail-item">
              <span class="detail-label">答对题数（不计主观题）：</span>
              <span class="detail-value">{{ record.correctCount }}/{{ record.totalCount }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">练习内容：</span>
              <span class="detail-value">{{ formatPracticeContent(record.subjects) }}</span>
            </div>
          </div>
          <div class="record-actions">
            <el-button type="text" class="detail-btn" @click="showDailyPracticeDetail(record.practiceId)">
              查看详情
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalRecords"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" background />
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'
import { useUserStore } from '@/store/user'
import { storeToRefs } from 'pinia'
import { useRouter, useRoute } from 'vue-router'

export default {
  name: 'TrainingRecord',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const userStore = useUserStore()
    const { userId } = storeToRefs(userStore)

    // 筛选条件
    const startDate = ref('')
    const endDate = ref('')
    const keyword = ref('')

    // 分页
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalRecords = ref(0)

    // 数据
    const records = ref([])
    const loading = ref(false)
    const activeTab = ref('real') // 默认显示真题考试

    // 计算属性
    const startIndex = computed(() => {
      return (currentPage.value - 1) * pageSize.value + 1
    })

    const endIndex = computed(() => {
      const end = currentPage.value * pageSize.value
      return end > totalRecords.value ? totalRecords.value : end
    })

    // 日期禁用规则
    const disabledStartDate = (time) => {
      if (endDate.value) {
        return time.getTime() > new Date(endDate.value).getTime()
      }
      return false
    }

    const disabledEndDate = (time) => {
      if (startDate.value) {
        return time.getTime() < new Date(startDate.value).getTime()
      }
      return false
    }

    // 格式化日期
    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD')
    }

    // 格式化每日练习内容
    const formatPracticeContent = (subjects) => {
      if (!subjects) return '无练习内容';
      
      if (typeof subjects === 'string') {
        const subjectArray = subjects.split(',');
        return subjectArray.join('，');
      }
      
      if (Array.isArray(subjects)) {
        return subjects.map(sub => `${sub.subject} ${sub.count}题`).join('，');
      }
      
      return '无练习内容';
    };

    // 获取考试记录
    const fetchRecords = async () => {
      if (!userId.value) {
        ElMessage.error('请先登录')
        return
      }

      try {
        loading.value = true

        if (activeTab.value === 'mock') {
          const response = await axios.get('/api/mock-exams/search', {
            params: {
              userId: userId.value,
              startDate: startDate.value,
              endDate: endDate.value,
              keyword: keyword.value,
              page: currentPage.value - 1,
              size: pageSize.value
            }
          })

          records.value = response.data.map(record => ({
            ...record,
            examStrategy: formatStrategy(record.examStrategy)
          }))
          totalRecords.value = response.data.length
        } else if (activeTab.value === 'real') {
          const response = await axios.get('/api/past-exams/search', {
            params: {
              userId: userId.value,
              startDate: startDate.value,
              endDate: endDate.value,
              keyword: keyword.value,
              page: currentPage.value - 1,
              size: pageSize.value
            }
          })

          records.value = response.data
          totalRecords.value = response.data.length
        } else if (activeTab.value === 'daily') {
          const response = await axios.get('/api/daily-practices/records', {
            params: {
              userId: userId.value,
              startDate: startDate.value,
              endDate: endDate.value,
              keyword: keyword.value,
              page: currentPage.value - 1,
              size: pageSize.value
            }
          });
          
          const responseData = response.data;
          const isPaginated = responseData.content !== undefined;
          
          records.value = (isPaginated ? responseData.content : responseData).map(record => ({
            practiceId: record.practiceId || record.practice_id,
            practiceDate: record.practiceDate || record.practice_date,
            subjects: record.subjects || record.subject_list || '无科目信息',
            totalCount: record.totalCount || record.total_count || 0,
            correctCount: record.correctCount || record.correct_count || 0
          }));

          totalRecords.value = isPaginated 
            ? responseData.totalElements || responseData.total 
            : responseData.length;
        }

      } catch (error) {
        console.error('获取记录失败:', error);
        records.value = [];
        totalRecords.value = 0;
        ElMessage.error('获取记录失败');
      } finally {
        loading.value = false
      }
    }

    // 策略格式化方法
    const formatStrategy = (strategy) => {
      if (!strategy) return '未指定策略'
      
      const strategyMap = {
        'weakness': '薄弱知识点',
        'high_frequency': '高频易错题',
        'random': '完全随机',
        'custom': '定向知识点',
        '薄弱知识点': '薄弱知识点',
        '高频易错题': '高频易错题',
        '完全随机': '完全随机',
        '定向知识点': '定向知识点'
      }
      return strategyMap[strategy] || strategy;
    }

    // 查看详情
    const showRecordDetail = (id) => {
      if (activeTab.value === 'mock') {
        router.push({
          name: 'MockExamDetail',
          params: { examId: id }
        })
      } else {
        router.push({
          name: 'PastExamDetail',
          params: { recordId: id }
        })
      }
    }

    const showDailyPracticeDetail = (practiceId) => {
      router.push({
        name: 'DailyPracticeDetail',
        query: { 
          practiceId,
          userId: userId.value
        }
      });
    }

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchRecords()
    }

    // 重置
    const handleReset = () => {
      startDate.value = ''
      endDate.value = ''
      keyword.value = ''
      currentPage.value = 1
      fetchRecords()
    }

    // 分页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchRecords()
    }

    // 当前页改变
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchRecords()
    }

    // 切换标签页
    const switchTab = (tab) => {
      activeTab.value = tab
      currentPage.value = 1
      fetchRecords()
    }

    // 初始化加载数据
    onMounted(() => {
      userStore.initialize()
      if (route.query.fromMockDetail) {
        switchTab('mock')
      } else {
        fetchRecords()
      }
    })

    return {
      startDate,
      endDate,
      keyword,
      currentPage,
      pageSize,
      totalRecords,
      records,
      loading,
      activeTab,
      startIndex,
      endIndex,
      disabledStartDate,
      disabledEndDate,
      formatDate,
      formatPracticeContent,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      switchTab,
      showRecordDetail,
      showDailyPracticeDetail
    }
  }
}
</script>

<style scoped>
.training-record-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
}

.header {
  margin-bottom: 20px;
}

.header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
  padding: 10px 0;
  border-bottom: 1px solid #e6e6e6;
}

.filter-section {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  padding: 20px;
}

.filter-content {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: flex-end;
}

.filter-group {
  flex: 1;
  min-width: 300px;
}

.filter-group h3 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #606266;
}

.date-inputs {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-separator {
  color: #909399;
  padding: 0 5px;
}

.keyword-input {
  width: 100%;
}

.filter-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 3px;
}

.search-btn,
.reset-btn {
  width: 80px;
}

.exam-type-tabs {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.tab-btn {
  padding: 12px 24px;
}

.exam-records {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 10px;
}

.record-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  min-height: calc((var(--row-count, 2) * (200px + 20px)));
}

.record-list[data-per-page="10"] {
  --row-count: 2;
}
.record-list[data-per-page="20"] {
  --row-count: 4;
}
.record-list[data-per-page="50"] {
  --row-count: 10;
}
.record-list[data-per-page="100"] {
  --row-count: 20;
}

.record-item {
  height: 150px;
  padding: 20px;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #ebeef5;
  transition: all 0.3s;
}

.record-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.exam-type {
  font-size: 16px;
  font-weight: 500;
  color: #409eff;
}

.exam-date {
  font-size: 12px;
  color: #909399;
}

.record-details {
  margin-bottom: 15px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.detail-label {
  color: #909399;
}

.detail-value {
  color: #606266;
  font-weight: 500;
}

.record-actions {
  text-align: right;
}

.detail-btn {
  color: #409eff;
  padding: 0;
}

.loading {
  padding: 20px;
}

.no-data {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-container {
  padding: 10px 0;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .filter-content {
    flex-direction: column;
  }

  .filter-group {
    width: 100%;
    min-width: auto;
  }

  .record-list {
    grid-template-columns: 1fr;
    min-height: auto;
  }

  .record-item {
    height: auto;
    min-height: 180px;
  }

  .exam-type-tabs {
    flex-wrap: wrap;
  }
  
  .tab-btn {
    flex: 1;
    min-width: 100px;
  }
}
</style>